package ru.arriah.servicedesk.web.admin.action;

import java.io.IOException;
import java.util.Collection;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;

public class DisplayEmployeesListAction extends DumbAction {
  protected EmployeeManagerLocalHome employeeManagerHome;
  
  public DisplayEmployeesListAction() throws NamingException {
    super();
    
    employeeManagerHome = 
      Utils.getEmployeeManagerHomeInterface();    
  }

  
  public String execute(ActionMapping actionMapping,
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    try {                
      EmployeeManagerLocalObject employeeManager = 
        employeeManagerHome.create();
      
      String status;
      String order = request.getParameter("order");
      String orderBy = request.getParameter("orderBy");
      String type = request.getParameter("type");
      
      order = (order == null) ? "" : order;                
      orderBy = (orderBy == null) ? "" : orderBy;
      type = (type == null) ? "" : type;
      
      if (type.equals("all")) {
        status = "'active', 'inactive'";
      } else if(type.equals("active")) {
        status = "'active'";
      } else if(type.equals("inactive")) {
        status = "'inactive'";
      } else 
        status = "'active'";
      
      Collection<EmployeeBean> employessList = 
        employeeManager.selectAll(          
          orderBy,
          order,
          status
        );
      
      employeeManager.remove();
      
      request.setAttribute("employessList", employessList);
      
      request.setAttribute("order", (order.equals("ASC") ? "DESC" : "ASC"));
      request.setAttribute("type", type);
      

      return actionMapping.getSuccessTarget();
    } catch (Exception e) {
      handleException(e, "execute");
      throw new InternalException("ErrorMessage.internal");
    }
  }
}